package com.qkun.library.widget;

import android.graphics.Outline;
import android.os.Build;
import android.view.View;
import android.view.ViewOutlineProvider;

import androidx.annotation.RequiresApi;

import com.qkun.library.utils.MyLog;
import com.qkun.library.utils.Utils;

public final class OutlineCreator {

    private static final String TAG = "OutlineProviderFactory";

    private OutlineCreator() {
    }

    @RequiresApi(api = Build.VERSION_CODES.KITKAT)
    public static <T extends MyOutlineProvider> T create(Class<T> cls) {
        T instance = null;
        try {
            instance = cls.newInstance();
        } catch (IllegalAccessException | InstantiationException e) {
            MyLog.e(TAG, e);
        }
        return Utils.requireNonNull(instance);
    }

    @RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
    public static abstract class MyOutlineProvider extends ViewOutlineProvider {
        public void bind(View view) {
            Utils.requireNonNull(view);
            view.setClipToOutline(true);
            view.setOutlineProvider(this);
        }
    }

    public static class Oval extends MyOutlineProvider {
        @RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
        @Override
        public void getOutline(View view, Outline outline) {
            outline.setOval(0, 0, view.getWidth(), view.getHeight());
        }
    }

    public static class Round extends MyOutlineProvider {

        private float mRadius;

        public Round setRadius(float radius) {
            this.mRadius = radius;
            return this;
        }

        @RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
        @Override
        public void getOutline(View view, Outline outline) {
            outline.setRoundRect(0, 0, view.getWidth(), view.getHeight(), mRadius);
        }
    }

    @RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
    public static class Custom extends MyOutlineProvider {

        private Outline mOutline;

        public Custom setOutline(Outline outline) {
            this.mOutline = outline;
            return this;
        }

        @Override
        public void getOutline(View view, Outline outline) {
            outline.set(mOutline);
        }
    }
}
